package com.ctshk.rpc.localfun.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ctshk.common.enums.SystemError;
import com.ctshk.common.exception.BusinessException;
import com.ctshk.common.utils.DateUtil;
import com.ctshk.rpc.localfun.dto.LocalFunOfflineSelCustomDTO;
import com.ctshk.rpc.localfun.entity.LocalFunProductCostStrategySpecStock;
import com.ctshk.rpc.localfun.entity.LocalFunProductSaleRecord;
import com.ctshk.rpc.localfun.mapper.LocalFunProductCostStrategySpecStockMapper;
import com.ctshk.rpc.localfun.mapper.LocalFunProductSaleRecordMapper;
import com.ctshk.rpc.localfun.req.LocalFunProductCostReq;
import com.ctshk.rpc.localfun.req.LocalFunStockReq;
import com.ctshk.rpc.localfun.service.ILocalFunCostPriceService;
import com.ctshk.rpc.localfun.service.ILocalFunProductSaleRecordService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.LocalTime;
import java.util.List;

/**
 * @Description
 * @Author wansi <gaylen15527491065@yeah.net>
 * @Date 2021/4/8
 */
@DubboService
public class LocalFunProductSaleRecordServiceImpl extends ServiceImpl<LocalFunProductSaleRecordMapper, LocalFunProductSaleRecord> implements ILocalFunProductSaleRecordService {

    @Autowired
    private LocalFunProductCostStrategySpecStockMapper costStrategySpecStockMapper;

    @DubboReference
    private ILocalFunCostPriceService iLocalFunCostPriceService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void operateStock(LocalFunStockReq localFunStockReq) {
        QueryWrapper<LocalFunProductCostStrategySpecStock> queryWrapper = new QueryWrapper<>();
        if(localFunStockReq.getAttrId1() != null){
            queryWrapper.lambda().eq(LocalFunProductCostStrategySpecStock::getAttr1Id,localFunStockReq.getAttrId1());
        }
        if(localFunStockReq.getAttrId2() != null){
            queryWrapper.lambda().eq(LocalFunProductCostStrategySpecStock::getAttr2Id,localFunStockReq.getAttrId2());
        }
        List<LocalFunProductCostStrategySpecStock> costStrategySpecStocks =
                costStrategySpecStockMapper.selectList(queryWrapper);

        //1.扣减库存

        //规格成本价库存信息
        LocalFunProductCostStrategySpecStock specStock = costStrategySpecStocks.stream().findFirst().orElse(null);
        if(specStock != null){
            QueryWrapper<LocalFunProductSaleRecord> saleRecordQueryWrapper = new QueryWrapper<>();
            saleRecordQueryWrapper.lambda().eq(LocalFunProductSaleRecord::getProductId,localFunStockReq.getProductId());
            List<LocalFunProductSaleRecord> localFunProductSaleRecords = baseMapper.selectList(saleRecordQueryWrapper);

            if(localFunProductSaleRecords.size() != 0){
                //该产品已售数量
                int soldStock = localFunProductSaleRecords.stream().mapToInt(LocalFunProductSaleRecord::getSoldNumber).sum();
                //已售库存
                specStock.setSoldStock(soldStock+localFunStockReq.getNum());
                //剩余库存=成本库存-产品已售库存
                specStock.setSurplusStock(specStock.getTotalStock()-soldStock-localFunStockReq.getNum());
            }else {
                specStock.setSoldStock(localFunStockReq.getNum());
                //剩余库存
                specStock.setSurplusStock(specStock.getTotalStock()-localFunStockReq.getNum());
            }
            costStrategySpecStockMapper.updateById(specStock);
        }

        LocalFunProductCostReq req = new LocalFunProductCostReq();
        req.setUserId(localFunStockReq.getUserId());
        req.setProductId(localFunStockReq.getProductId());
        req.setQueryDate(LocalDate.now());
        req.setChannelType(1);
        LocalFunOfflineSelCustomDTO increaseFee = iLocalFunCostPriceService.getIncreaseFee(req);
        if(increaseFee == null){
            throw new BusinessException(SystemError.LOCAL_FUN_18004);
        }
        //2.创建售卖记录
        LocalFunProductSaleRecord record = new LocalFunProductSaleRecord();
        //1 线上 2线下
        record.setLine(localFunStockReq.getLine());
        //自營渠道 1 代理商 2 官方 3 平台 4
        record.setChannel(localFunStockReq.getChannel());
        //勾选人/部门类型(2部门，1员工)
        record.setCheckType(increaseFee.getCheckType());
        record.setOrderId(localFunStockReq.getOrderId());
        //线下 部门：部门ID ,人员：人员ID;线上--渠道ID
        record.setCustomId(localFunStockReq.getCustomId());
        record.setCustomName(localFunStockReq.getCustomName());
        record.setSalesDate(DateUtil.localTimeToDate(LocalTime.now()));
        record.setProductId(localFunStockReq.getProductId());
        record.setSoldNumber(localFunStockReq.getNum());
        record.setIsDeleted(0);
        record.setId(IdWorker.getId());
        baseMapper.insert(record);
    }

    @Override
    public void backToStock(Long orderId, Long productId, Long attrId1, Long attrId2, Integer ticketNum, Long userId) {
        QueryWrapper<LocalFunProductCostStrategySpecStock> queryWrapper = new QueryWrapper<>();
        if(attrId1 != null){
            queryWrapper.lambda().eq(LocalFunProductCostStrategySpecStock::getAttr1Id,attrId1);
        }
        if(attrId2 != null){
            queryWrapper.lambda().eq(LocalFunProductCostStrategySpecStock::getAttr2Id,attrId2);
        }
        List<LocalFunProductCostStrategySpecStock> costStrategySpecStocks =
                costStrategySpecStockMapper.selectList(queryWrapper);
        //1.還库存
        //规格成本价库存信息
        LocalFunProductCostStrategySpecStock specStock = costStrategySpecStocks.stream().findFirst().orElse(null);
        if(specStock != null){
            //该产品總已售庫存數
            int soldStock = baseMapper.selectSoldStockCount(productId);
            //查詢該訂單售賣庫存數
            int orderSoldStockCount = baseMapper.selectOrderSoldStockCount(productId, orderId);
            //已售库存 去掉取消訂單的庫存數
            specStock.setSoldStock(soldStock-orderSoldStockCount);
            //剩余库存 加上取消訂單的庫存數
            specStock.setSurplusStock(specStock.getTotalStock()+orderSoldStockCount);
            costStrategySpecStockMapper.updateById(specStock);
        }
        //2. 刪除該訂單的售賣庫存記錄
        QueryWrapper<LocalFunProductSaleRecord> saleRecordQueryWrapper = new QueryWrapper<>();
        saleRecordQueryWrapper.lambda().eq(LocalFunProductSaleRecord::getProductId,productId);
        saleRecordQueryWrapper.lambda().eq(LocalFunProductSaleRecord::getOrderId,orderId);
        baseMapper.delete(saleRecordQueryWrapper);
    }
}
